package com.eystar.pdc.directive;

import java.util.Set;

import javax.servlet.http.HttpSession;

import com.eystar.pdc.model.User;
import com.eystar.pdc.util.LoginUtil;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;

/**
 * <pre>
 * 判断是否有权限tag1
 * #auth_has("tag1")
 * 	body
 * #end
 * 
 * </pre>
 * @author Administrator
 *
 */
public class AuthHasDirective extends Directive {
	
	public void setExprList(ExprList exprList) {
		int len = exprList.length();
		if (len != 1) {
			throw new ParseException("指令#auth_has只能一个参数", location);
		}
		super.setExprList(exprList);
	}

	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		HttpSession session = (HttpSession) scope.get("session");
		User user = (User) session.getAttribute(LoginUtil.SESSION_CURRENT_USER);
		if (user != null) {
			Set<String> authorities = user.get("authorities");
			String authTag = (String) exprList.getFirstExpr().eval(scope);
			if (authorities.contains(authTag)) {
				stat.exec(env, scope, writer);
			}
		}
	}

	/**
	 * 当只有一个参数的时候，必须要有
	 */
	@Override
	public boolean hasEnd() {
		return true;
	}
}
